<!-- src/views/IncomeExpenseManagement.vue -->
<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <PageHeader title="收支项目管理">
      <!-- 搜索和筛选区域 -->
      <template #search-filters>
        <div class="income-expense-search">
          <span class="label">项目名称：</span>
          <el-input
            v-model="searchParams.search"
            placeholder="收支项目名称"
            style="width: 300px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Document /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="status-select">
          <span class="label">状态：</span>
          <el-select
            v-model="searchParams.zt"
            placeholder="状态"
            clearable
            style="width: 150px"
            @change="handleFilterChange"
          >
            <el-option label="全部" value="" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </div>
      </template>

      <!-- 主要操作按钮 -->
      <template #main-actions>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增项目
        </el-button>
        <el-button type="success" @click="handleAddChild" :disabled="!selectedNode">
          <el-icon><FolderAdd /></el-icon>
          新增子项目
        </el-button>
      </template>

      <!-- 更多操作下拉菜单 -->
      <template #more-actions>
        <el-dropdown @command="handleMoreAction">
          <el-button type="info">
            <el-icon><More /></el-icon>
            更多
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="reset" icon="Refresh">重置筛选</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </PageHeader>

    <!-- 树状结构展示 -->
    <div class="table-container">
      <div class="tree-container">
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="treeProps"
          :expand-on-click-node="false"
          :highlight-current="true"
          node-key="id"
          @node-click="handleNodeClick"
          @node-expand="handleNodeExpand"
          @node-collapse="handleNodeCollapse"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <div class="node-content">
                <span class="node-name">{{ data.szxmmc }}</span>
                <span class="node-path" v-if="data.treePath">
                  ({{ data.treePath }})
                </span>
                <el-tag size="small" :type="data.zt === 1 ? 'success' : 'danger'" class="status-tag">
                  {{ data.zt === 1 ? '启用' : '禁用' }}
                </el-tag>
              </div>
              <div class="node-actions">
                <el-button type="primary" size="small" @click.stop="handleEdit(data)">
                  编辑
                </el-button>
                <el-button type="success" size="small" @click.stop="handleAddChild(data)">
                  子项目
                </el-button>
                <el-button type="danger" size="small" @click.stop="handleDelete(data)">
                  删除
                </el-button>
              </div>
            </div>
          </template>
        </el-tree>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      class="management-dialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="dialog-form"
      >
        <el-form-item label="上级项目" v-if="showParentSelect">
          <el-tree-select
            v-model="formData.parentId"
            :data="parentOptions"
            :props="treeSelectProps"
            placeholder="请选择上级项目"
            style="width: 100%"
            clearable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="szxmmc">
          <el-input v-model="formData.szxmmc" placeholder="请输入收支项目名称" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.zt" style="width: 100%">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  FolderAdd,
  Search,
  Refresh,
  Document,
  More
} from '@element-plus/icons-vue'
import * as incomeExpenseApi from '@/api/incomeExpenseApi'
import PageHeader from '@/components/layout/PageHeader.vue'
import '@/styles/page.css'

// 树状数据
const treeData = ref([])
const treeRef = ref()
const selectedNode = ref(null)

// 搜索参数
const searchParams = reactive({
  search: '',
  zt: ''
})

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('新增项目')
const isEditMode = ref(false)
const showParentSelect = ref(true)

// 表单数据
const formRef = ref()
const formData = reactive({
  id: null,
  szxmmc: '',
  parentId: 0,
  zt: 1
})

// 父级选项
const parentOptions = ref([])

// 树状配置
const treeProps = {
  children: 'children',
  label: 'szxmmc'
}

const treeSelectProps = {
  children: 'children',
  label: 'szxmmc',
  value: 'id'
}

// 表单验证规则
const formRules = {
  szxmmc: [
    { required: true, message: '请输入收支项目名称', trigger: 'blur' },
    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ]
}

// 加载树状数据
const loadTreeData = async () => {
  try {
    const response = await incomeExpenseApi.getTreeStructure()
    console.log('Tree structure response:', response)
    const data = response.data || []
    if (Array.isArray(data)) {
      treeData.value = buildTree(data)
    } else {
      console.warn('Tree structure data is not an array:', data)
      treeData.value = []
    }
  } catch (error) {
    console.error('加载树状数据失败:', error)
    ElMessage.error('加载数据失败')
    treeData.value = []
  }
}

// 构建树状结构
const buildTree = (data) => {
  // 验证数据是否为数组
  if (!Array.isArray(data)) {
    console.warn('buildTree: data is not an array', data)
    return []
  }
  
  const map = {}
  const result = []

  // 创建映射
  data.forEach(item => {
    map[item.id] = { ...item, children: [] }
  })

  // 构建树状结构
  data.forEach(item => {
    const node = map[item.id]
    if (item.parentId === 0 || item.parentId === null || item.parentId === undefined || !map[item.parentId]) {
      result.push(node)
    } else {
      map[item.parentId].children.push(node)
    }
  })

  return result
}

// 加载父级选项
const loadParentOptions = async () => {
  try {
    const response = await incomeExpenseApi.getTreeStructure()
    console.log('Parent options response:', response)
    const data = response.data || []
    if (Array.isArray(data)) {
      parentOptions.value = buildTree(data)
    } else {
      console.warn('Parent options data is not an array:', data)
      parentOptions.value = []
    }
  } catch (error) {
    console.error('加载父级选项失败:', error)
    parentOptions.value = []
  }
}

// 搜索处理
const handleSearch = () => {
  loadTreeData()
}

// 筛选变化处理
const handleFilterChange = () => {
  handleSearch()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchParams, {
    search: '',
    zt: ''
  })
  handleSearch()
}

// 更多操作处理
const handleMoreAction = (command) => {
  switch (command) {
    case 'reset':
      handleReset()
      break
    default:
      break
  }
}

// 节点点击处理
const handleNodeClick = (data) => {
  selectedNode.value = data
}

// 节点展开处理
const handleNodeExpand = async (data) => {
  if (!data.children || data.children.length === 0) {
    try {
      const response = await incomeExpenseApi.getChildrenByParentId(data.id)
      console.log('Children response for parent', data.id, ':', response)
      const childrenData = response.data || []
      if (Array.isArray(childrenData)) {
        data.children = childrenData.filter(item => item.parentId === data.id)
      } else {
        console.warn('Children data is not an array:', childrenData)
        data.children = []
      }
    } catch (error) {
      console.error('加载子节点失败:', error)
      data.children = []
    }
  }
}

// 节点折叠处理
const handleNodeCollapse = (data) => {
  // 可以在这里添加折叠逻辑
}

// 新增项目
const handleAdd = () => {
  dialogTitle.value = '新增项目'
  isEditMode.value = false
  showParentSelect.value = true
  Object.assign(formData, {
    id: null,
    szxmmc: '',
    parentId: 0,
    zt: 1
  })
  loadParentOptions()
  dialogVisible.value = true
}

// 新增子项目
const handleAddChild = (parentData) => {
  dialogTitle.value = '新增子项目'
  isEditMode.value = false
  showParentSelect.value = true
  Object.assign(formData, {
    id: null,
    szxmmc: '',
    parentId: parentData ? parentData.id : 0,
    zt: 1
  })
  loadParentOptions()
  dialogVisible.value = true
}

// 编辑项目
const handleEdit = (data) => {
  dialogTitle.value = '编辑项目'
  isEditMode.value = true
  showParentSelect.value = true
  Object.assign(formData, {
    id: data.id,
    szxmmc: data.szxmmc,
    parentId: data.parentId || 0,
    zt: data.zt
  })
  loadParentOptions()
  dialogVisible.value = true
}

// 删除项目
const handleDelete = async (data) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除项目"${data.szxmmc}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await incomeExpenseApi.deleteIncomeExpenseTree(data.id)
    ElMessage.success('删除成功')
    loadTreeData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      if (error.message && error.message.includes('子项目')) {
        ElMessage.error('无法删除，该项目下还有子项目')
      } else {
        ElMessage.error('删除失败')
      }
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (isEditMode.value) {
      await incomeExpenseApi.updateIncomeExpenseTree(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      await incomeExpenseApi.createIncomeExpenseTree(formData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadTreeData()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.message && error.message.includes('已存在')) {
      ElMessage.error('收支项目名称已存在')
    } else {
      ElMessage.error('提交失败')
    }
  }
}

// 页面初始化
onMounted(() => {
  loadTreeData()
})
</script>

<style scoped>
/* 搜索筛选样式 */
.income-expense-search,
.status-select {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  font-size: 14px;
  color: var(--text-secondary, #606266);
  white-space: nowrap;
}

.tree-container {
  padding: 20px;
  height: 100%;
  overflow: auto;
}

.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 5px 0;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.node-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.node-path {
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

.status-tag {
  margin-left: 10px;
}

.node-actions {
  display: flex;
  gap: 5px;
  opacity: 0;
  transition: opacity 0.3s;
}

.tree-node:hover .node-actions {
  opacity: 1;
}

@media (max-width: 768px) {
  .node-actions {
    opacity: 1;
  }
}
</style> 